package io

import (
	"jvmgo/native"
	"jvmgo/rtda"
	"jvmgo/rtda/heap"
	"os"
	"path/filepath"
)

func init() {
	native.Register("java/io/UnixFileSystem", "getBooleanAttributes0", "(Ljava/io/File;)I", getBooleanAttributes0)
	native.Register("java/io/UnixFileSystem", "canonicalize0", "(Ljava/lang/String;)Ljava/lang/String;", canonicalize0)

}

func canonicalize0(frame *rtda.Frame) {
	vars := frame.LocalVars()
	path := vars.GetRef(1)
	goPath := heap.GoString(path)
	goPath2 := filepath.Clean(goPath)
	if goPath2 != goPath {
		path = heap.JString(frame.Method().Loader(), goPath2)
	}
	stack := frame.OperandStack()
	stack.PushRef(path)
}

func getBooleanAttributes0(frame *rtda.Frame) {
	vars := frame.LocalVars()
	var1 := vars.GetRef(1)
	path := var1.GetRefVar("path", "Ljava/lang/String;")
	pathStr := heap.GoString(path)
	attributes0 := 0
	if _exists(pathStr) {
		attributes0 |= 0x01
	}
	if _isDir(pathStr) {
		attributes0 |= 0x04
	}
	stack := frame.OperandStack()
	stack.PushInt(int32(attributes0))
}

func _isDir(path string) bool {
	fileInfo, err := os.Stat(path)
	if err == nil {
		return fileInfo.IsDir()
	}
	return false

}

func _exists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	return false
}
